<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\model\SysSetting;
use app\service\upload\Upload;
use think\Request;

class UploadController extends BaseController
{
    protected  $type = [
        'file'    => 4,
        'image'    => 2,
        'video'    => 3,
        'mp3'    => 5,
        'zip'   => 1,
    ];

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     * @throws \app\exception\ModelException
     */
    public function save(Request $request)
    {
        if(request()->isPost()){
            $file = request()->file('file');
            if(empty($file)){
                return jsonReturn(-2,'文件不能为空');
            }
            $seller_id = $this->admin['seller_id'];
            // 查看文件类型
            $fileName = $file->getOriginalName();
            $fileExt = $file->getOriginalExtension();
            $file_type = fileFormat($fileName);
            $fileType = $this->type[$file_type];
            // 附件大小和类型验证
            // 获取上传配置
            $Settings = new SysSetting();
            $uploadSetting = $Settings->getAllCustomData(['parent_id'=>1,'group'=>'upload','status'=>1],'id desc','id,group,title,value')['data'];
            $uploadSetting = getColumnForKeyArray($uploadSetting,'title');
            $limitSize = $uploadSetting[$file_type.'_size']['value'] * 1024;     // byte
            $fileSize = $file->getSize();       // 单位byte
            if($fileSize > $limitSize){
                return jsonReturn(-1,'文件过大，请修改上传限制或者替换小的文件');
            }
            $extArr = explode(',',$uploadSetting[$file_type.'_ext']['value']);
            if(!in_array($fileExt,$extArr)){
                return jsonReturn(-2,'文件格式错误，请重新上传');
            }
            // 文件信息提取
            $where = [
                'seller_id' => $seller_id,
                'group' => 'upload',
                'title' => 'storage'
            ];
            $place = new SysSetting();
            $type = $place->getSysSetting($where)['data']->toArray()['value'];

            $upload = new Upload();
            $info = $upload->create($file,$seller_id, $type,$file_type);

            if ($info) {
                $uploadInfo = $upload->getUploadFileInfo();
                if ($uploadInfo['code'] == 0) {
                    $uploadInfo['data']['type'] = $fileType;
                    $uploadInfo['data']['size'] = round($fileSize / 1024,2);
                    $uploadInfo['data']['mime_type'] = $fileExt;
                }
                return json($uploadInfo);
            }else{
                return jsonReturn(-1, '上传失败请重新尝试');
            }
        }
        return jsonReturn(-3,'请求方法错误');
    }



}
